/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Client.Online;

import Client.Client;
import Client.ClientUtils;
import java.awt.Color;
import java.awt.Dimension;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JScrollPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.text.StyledDocument;

/**
 *
 * @author TienNT
 */
public class PrivateConversasion extends javax.swing.JFrame {

    Client mClient;
    String mDesClient;
    StyledDocument doc;

    /**
     * Creates new form PrivateConversasion
     */
    public PrivateConversasion() {
        initComponents();
    }

    public PrivateConversasion(Client client, String desClient, boolean isOnline, boolean isIgnored) {
        mClient = client;
        mDesClient = desClient;
        setTitle(mClient.getClientName());
        initComponents();
        lblStatus.setText(desClient);
        txtMessage.requestFocus();
        if (!isOnline) {
            jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/offline.png")));
        } else {
            jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/online.png")));
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        txtMessage = new javax.swing.JTextField();
        btnSend = new javax.swing.JButton();
        lblStatus = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        textPaneConversation = new javax.swing.JTextPane();
        btnBuzz = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        btnSendFile = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        menuClose = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        txtMessage.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtMessageActionPerformed(evt);
            }
        });

        btnSend.setText("Send");
        btnSend.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSendActionPerformed(evt);
            }
        });

        lblStatus.setText(mClient.getClientName());

        doc=textPaneConversation.getStyledDocument();
        addStylesToDocument(doc);
        textPaneConversation.setEditable(false);
        jScrollPane1.setViewportView(textPaneConversation);

        btnBuzz.setText("BUZZ!");
        btnBuzz.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBuzzActionPerformed(evt);
            }
        });

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/online.png"))); // NOI18N
        jLabel1.setText("jLabel1");

        btnSendFile.setText("Send File");
        btnSendFile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSendFileActionPerformed(evt);
            }
        });

        jMenu1.setText("Conversasion");

        menuClose.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ESCAPE, 0));
        menuClose.setText("Close");
        menuClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuCloseActionPerformed(evt);
            }
        });
        jMenu1.add(menuClose);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Edit");
        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(btnBuzz)
                                .addGap(186, 186, 186)
                                .addComponent(btnSendFile)
                                .addGap(0, 83, Short.MAX_VALUE))
                            .addComponent(txtMessage))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnSend))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(8, 8, 8)
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblStatus, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblStatus)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 247, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnBuzz)
                    .addComponent(btnSendFile))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtMessage, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnSend, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        jScrollPane1.setVerticalScrollBarPolicy(
            JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        jScrollPane1.setPreferredSize(new Dimension(250, 155));
        jScrollPane1.setMinimumSize(new Dimension(10, 10));

        pack();
    }// </editor-fold>//GEN-END:initComponents

    public void setPeerOnline() {
        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/online.png")));
        updateConversasion("notify", mDesClient+" has logged in");
    }

    public void setPeerOffline() {
        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/offline.png")));
        updateConversasion("notify", mDesClient+" has logged out");
    }

    private void btnSendActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSendActionPerformed
        // TODO add your handling code here:
        sendMessage();
    }//GEN-LAST:event_btnSendActionPerformed

    private void txtMessageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtMessageActionPerformed
        // TODO add your handling code here:
        sendMessage();
        btnSend.setEnabled(false);
    }//GEN-LAST:event_txtMessageActionPerformed

    private void btnBuzzActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuzzActionPerformed
        // TODO add your handling code here:
        mClient.sendMessageToServer(ClientUtils.BUZZ_REQUEST + ":" + mDesClient);
        new BtnBuzzInvi(btnBuzz).start();
    }//GEN-LAST:event_btnBuzzActionPerformed

    private void btnSendFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSendFileActionPerformed
        // TODO add your handling code here:
        String path = null;
        JFileChooser fc = new JFileChooser("D:\\");
        fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
        fc.setMultiSelectionEnabled(false);
        int check = fc.showDialog(this, null);
        if (check == JFileChooser.APPROVE_OPTION) {
            path = fc.getSelectedFile().getPath();
            String command = "" + ClientUtils.ASK_FILE_TRANSFER + ";" + mClient.getClientName() + ";" + mDesClient + ";" + path;
            mClient.sendMessageToServer(command);
        }
    }//GEN-LAST:event_btnSendFileActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        // TODO add your handling code here:
        mClient.getDashboard().mPrivateConversasionList.remove(mDesClient);
    }//GEN-LAST:event_formWindowClosing

    private void menuCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuCloseActionPerformed
        // TODO add your handling code here:
        mClient.getDashboard().mPrivateConversasionList.remove(mDesClient);
        dispose();
    }//GEN-LAST:event_menuCloseActionPerformed
    public void sendMessage() {
        if (txtMessage.getText().equals("")) {
            return;
        }
        String command = "" + ClientUtils.NEW_PRIVATE_MESSAGE + ":"
                + mClient.getClientName() + ":" + mDesClient + ":"
                + txtMessage.getText();
        updateConversasion(mClient.getClientName(), txtMessage.getText());
        txtMessage.setText("");
        btnSend.setEnabled(false);
        mClient.sendMessageToServer(command);
    }

    public void buzzExe() throws InterruptedException {
        this.setLocation(this.getLocation().x - 5, this.getLocation().y - 5);
        Thread.sleep(50);
        this.setLocation(this.getLocation().x + 10, this.getLocation().y + 10);
        Thread.sleep(50);
        this.setLocation(this.getLocation().x - 5, this.getLocation().y + 5);
        Thread.sleep(50);
        this.setLocation(this.getLocation().x + 10, this.getLocation().y - 10);
        Thread.sleep(50);

        this.setLocation(this.getLocation().x - 5, this.getLocation().y + 5);

    }

    private void addStylesToDocument(StyledDocument doc) {
        //Initialize some styles.
        Style def = StyleContext.getDefaultStyleContext().
                getStyle(StyleContext.DEFAULT_STYLE);

        Style fromOther = doc.addStyle("fromOther", def);
        StyleConstants.setBold(fromOther, true);
        StyleConstants.setForeground(fromOther, new Color(51, 51, 153));

        Style fromMe = doc.addStyle("fromMe", def);
        StyleConstants.setBold(fromMe, true);
        StyleConstants.setForeground(fromMe, new Color(128, 128, 128));

        Style content = doc.addStyle("content", def);
        StyleConstants.setForeground(content, Color.black);

        Style notify = doc.addStyle("notify", def);
        StyleConstants.setBold(notify, true);
        StyleConstants.setForeground(notify, new Color(102, 102, 102));
        StyleConstants.setBackground(notify, new Color(247, 247, 247));

        Style buzz = doc.addStyle("buzz", def);
        StyleConstants.setBold(buzz, true);
        StyleConstants.setForeground(buzz, Color.red);
    }

    public void updateConversasion(String from, String message) {
        try {
            if (from.equals("buzz")) {
                doc.insertString(doc.getLength(), message + "\n", doc.getStyle("buzz"));
                return;
            } else if (from.equals("notify")) {
                doc.insertString(doc.getLength(), message + "\n",
                        doc.getStyle("notify"));
                return;
            } else if (from.equals(mClient.getClientName())) {
                doc.insertString(doc.getLength(), from + "  :  ",
                        doc.getStyle("fromMe"));
            } else {
                doc.insertString(doc.getLength(), from + "  :  ",
                        doc.getStyle("fromOther"));
            }
            doc.insertString(doc.getLength(), message + "\n",
                    doc.getStyle("content"));
        } catch (BadLocationException ex) {
            Logger.getLogger(PrivateConversasion.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnBuzz;
    private javax.swing.JButton btnSend;
    private javax.swing.JButton btnSendFile;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblStatus;
    private javax.swing.JMenuItem menuClose;
    private javax.swing.JTextPane textPaneConversation;
    private javax.swing.JTextField txtMessage;
    // End of variables declaration//GEN-END:variables

    public class BtnBuzzInvi extends Thread {

        javax.swing.JButton btn;

        public BtnBuzzInvi(javax.swing.JButton btn) {
            this.btn = btn;
        }

        @Override
        public void run() {
            btn.setEnabled(false);
            try {
                Thread.sleep(15000);
            } catch (Exception e) {
            }
            btn.setEnabled(true);
        }
    }
}
